package com.hmdp.utils;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.Shop;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.utils.RedisConstants.*;

@Component
@Slf4j
@RequiredArgsConstructor
public class CacheClient {

    private final StringRedisTemplate stringRedisTemplate;

    /**
     * 缓存接口
     * @param key
     * @param value
     * @param expireTime
     * @param timeUnit
     */
    public void set(String key, Object value, Long expireTime, TimeUnit timeUnit) {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), expireTime, timeUnit);
    }

    /**
     * 逻辑过期缓存接口
     * @param key
     * @param value
     * @param expireTime
     * @param timeUnit
     */
    public void setWithLogicExpireTime(String key, Object value, Long expireTime, TimeUnit timeUnit) {
        //设置逻辑过期时间
        RedisData<Object> redisData = new RedisData<>();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(timeUnit.toSeconds(expireTime)));
        //写入Redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    /**
     * 缓存空值解决存穿透问题
     * @param keyPrefix
     * @param id
     * @param type
     * @param dbFallback
     * @param expireTime
     * @param timeUnit
     * @return
     * @param <ID>
     * @param <R>
     */
    public <ID, R> R queryWithPassThrough(
            String keyPrefix,
            ID id,
            Class<R> type,
            Function<ID, R> dbFallback,
            Long expireTime,
            TimeUnit timeUnit) {
        String key = keyPrefix + id;
        //1、查询Redis缓存商户
        String json = stringRedisTemplate.opsForValue().get(key);
        //2、判断商户缓存是否存在
        if (StrUtil.isNotBlank(json)) {
            //3、存在，直接返回商铺信息
            return JSONUtil.toBean(json, type);
        }
        //判断是否为空值
        if(json != null) {
            return null;
        }
        //4、不存在，根据id查询商铺信息
        R r = dbFallback.apply(id);
        if (r == null) {
            //将空值存入redis
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            //5、商铺信息不存在，返回错误
            //return Result.fail("查询的商户不存在");
            return null;
        }
        //6、商铺存在，写入Redis缓存
        this.set(key,r,expireTime,timeUnit);
        //7、返回
        return r;
    }

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    /**
     * 逻辑过期解决缓存击穿
     * @param id
     * @return
     */
    public <ID, R> R queryWithLogicalExpire(
            String keyPrefix,
            ID id,
            Class<R> type,
            Function<ID, R> dbFallback,
            Long expireTime,
            TimeUnit timeUnit) {
        String key = keyPrefix + id;
        //1、查询Redis缓存商户
        String json = stringRedisTemplate.opsForValue().get(key);
        //2、判断商户缓存是否存在
        if (StrUtil.isBlank(json)) {
            //3、不存在，直接返回null
            return null;
        }
        //4、存在，缓存命中，需要把json反序列化为对象判断是否过期
        RedisData<R> redisData = JSONUtil.toBean(json, new TypeReference<RedisData<R>>() {}, false);
        LocalDateTime now = LocalDateTime.now();
        R r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
        LocalDateTime expireTimeR = redisData.getExpireTime();
        if(now.isBefore(expireTimeR)) {
            //5.1未过期，直接返回店铺信息
            return r;
        }
        //5.2已过期，需要缓存重建
        String lockKey = LOCK_SHOP_KEY + id;
        //6.缓存重建
        // 6.1获取互斥锁
        boolean isLock = tryLock(lockKey);
        // 6.2判断是否获取锁成功
        if (isLock) {
            // 6.3成功，开启独立线程重建缓存
            CACHE_REBUILD_EXECUTOR.submit(()->{
                try {
                    //查询数据库
                    R r1 = dbFallback.apply(id);
                    //写入redis
                    this.setWithLogicExpireTime(key,r1,expireTime,timeUnit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    //释放锁
                    unlock(lockKey);
                }
            });
        }
        // 6.4失败，直接返回已过期的商铺信息
        //7、返回
        return r;
    }

    /**
     * 使用redis设置锁
     * @param key
     * @return
     */
    private boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.MINUTES);
        return BooleanUtil.isTrue(flag);
    }

    /**
     * 释放redis的锁
     * @param key
     */
    private void unlock(String key) {
        stringRedisTemplate.delete(key);
    }

}
